package com.open.common.utils;

import okhttp3.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtils {

    private static final Logger logger = LogManager.getLogger(HttpUtils.class);
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static OkHttpClient client;

    /**
     * 设置自定义的 OkHttpClient
     *
     * @param customClient 自定义的 OkHttpClient
     */
    public static void setClient(OkHttpClient customClient) {
        client = customClient;
    }

    // 初始化 OkHttpClient
    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS) // 连接超时
                .readTimeout(10, TimeUnit.SECONDS)    // 读取超时
                .writeTimeout(10, TimeUnit.SECONDS)   // 写入超时
                .build();
    }

    /**
     * 同步 GET 请求
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 响应结果
     * @throws IOException
     */
    public static String getSync(String url, Map<String, String> params) throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            logger.info("getSync url：{}, params:{},response:{}", url, params, response);
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

    /**
     * 异步 GET 请求
     *
     * @param url      请求地址
     * @param params   请求参数
     * @param callback 回调接口
     */
    public static void getAsync(String url, Map<String, String> params, Callback callback) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();

        client.newCall(request).enqueue(callback);
    }

    /**
     * 同步 POST 请求 (Map形式)
     *
     * @param url    请求地址
     * @param params 表单参数
     * @return 响应结果
     * @throws IOException
     */
    public static String postSync(String url, Map<String, String> params) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            logger.info("postSync map url：{}, params:{},response:{}", url, params, response);
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

    /**
     * 异步 POST 请求 (Map形式)
     *
     * @param url      请求地址
     * @param params   表单参数
     * @param callback 回调接口
     */
    public static void postAsync(String url, Map<String, String> params, Callback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();

        client.newCall(request).enqueue(callback);
    }

    /**
     * 同步 POST 请求 (JSON形式)
     *
     * @param url  请求地址
     * @param json JSON字符串
     * @return 响应结果
     * @throws IOException
     */
    public static String postSync(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            logger.info("postSync json url：{}, params:{},response:{}", url, json, response);
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

    /**
     * 异步 POST 请求 (JSON形式)
     *
     * @param url      请求地址
     * @param json     JSON字符串
     * @param callback 回调接口
     */
    public static void postAsync(String url, String json, Callback callback) {
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(callback);
    }
}